import { useHistory, useLocation } from 'react-router-dom'
import { InfiniteScroll, NavBar } from 'antd-mobile'

import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getSearchResults } from '@/store/actions/search'
import { RootState } from '@/types/store'
import ArticleItem from '@/pages/Home/ArticleItem'

const Result = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const location = useLocation()
  const params = new URLSearchParams(location.search)
  const keyword = params.get('keyword') || ''

  // 当前加载的页数及状态
  const [page, setPage] = useState(1)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    dispatch(getSearchResults(keyword, 1))
  }, [dispatch, keyword])

  const { results } = useSelector((state: RootState) => state.search)
  // console.log(results)
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {results.map((item) => (
          <div
            className="article-item"
            key={item.art_id}
            onClick={() => {
              history.push(`/article/${item.art_id}`)
            }}
          >
            <ArticleItem key={item.art_id} article={item} />
          </div>
        ))}
        <InfiniteScroll
          loadMore={async () => {
            if (loading) return
            setLoading(true)

            await dispatch(getSearchResults(keyword, page))

            setPage(page + 1)
            setLoading(false)
          }}
          hasMore={page <= 5}
        />
      </div>
    </div>
  )
}

export default Result
